const express = require("express")
const app = express();
const path = require("path");

//处理body请求体的中间件
app.use(express.urlencoded())
app.use(express.json())
app.use((req,res,netx)=>{
  res.set('Access-Control-Allow-Origin','*')
  res.set("Access-Control-Allow-Headers", "token")
  netx()
})
//cors跨域
app.get("/userInfo", (req, res) => {
  // console.log(req.query);
 
  //查询成功 响应
  res.send({
    code: 10000,
    msg: "查询成功",
    data: {
      name: "李博",
      age: 18,
      sex: "男"
    }
  })

})
//jsonp请求接口
app.get("/getUser", (req, res) => {
  console.log(req.query, "req.query");
  const {
    userId,
    cb
  } = req.query;
 const data = {
    code: 10000,
    msg: "查询成功",
    data: {
      name: "李博",
      age: 18,
      sex: "男"
    }
 }


 res.send(`${cb}(${JSON.stringify(data)})`)
  

 
})

app.post("/adduser", (req, res) => {
//   console.log("adduser");
//   console.log(req.body, "req.body");
//   console.log(req.query, "req.query");
  const {
    name,
    age,
    sex
  } = req.body;

  if (!name || !age || !sex) {
    return res.send({
      code: 10001,
      mes: "添加失败",
      data: null
    })
  }

  res.send({
    code: 10000,
    mes: "添加成功",
    data: null
  })
})


// //静态资源部署接口
// app.get("/1", (req, res) => {
//   const filePath = path.resolve(__dirname, "./01.jsonp跨域.html");
//   res.sendFile(filePath);
// })
// app.get("/2", (req, res) => {
//     const filePath = path.resolve(__dirname, "./02.Cors跨域.html");
//     res.sendFile(filePath);
//   })
  





app.listen(3030, () => {
  console.log("服务器请求成功 请访问 http://127.0.0.1:3030");
})